﻿'use strict';

if (zxcv && !zxcv.VisualNode) {
    zxcv.VisualNode = function () {
        this.opacity  = 1;
        this.visible  = false;
        this.parent   = null;
        this.children = [];
    };

    zxcv.VisualNode.prototype.show = function () { this.visible = true;  }
    zxcv.VisualNode.prototype.hide = function () { this.visible = false; }
    zxcv.VisualNode.prototype.addChild = function (item) {
        if (item.parent) {
            if (item.parent != this)
                item.parent.removeChild(item);
            else
                return;
        }

        item.parent = this;
        this.children.push(item);
    }

    zxcv.VisualNode.prototype.removeChild = function (item) {
        var i, length,
            children = this.children,
            child;

        // 제거할 자식 객체을 찾아서 뒤에 있는 자식 객체들을 앞으로 당긴 후에
        // 배열의 마지막 항목을 제거합니다.

        for (i = 0, length = children.length; i < length; i++) {
            child = children[i];
            if (child == item) {
                child.parent = null;
                break;
            }
        }

        length -= 1;
        for (; i < length; i++) {
            children[i] = children[i + 1];
            children[i + 1] = null;
        }

        children.pop();
    }

    zxcv.VisualNode.prototype.draw = function (g) {
        var i, length,
            children = this.children;

        for (i = 0, length = children.length; i < length; i++) {
            if (children[i])
                children[i].draw(g);
        }
    }

    ////////////////////////////////////////////////////////////////////////////////
    
    zxcv.SpriteNode = function (transform, texture, originX, originY, clippingRectangle) {
        zxcv.VisualNode.call(this);
        this.transform = transform;
        this.texture   = texture;
        this.originX   = originX;
        this.originY   = originY;
        this.clippingRectangle = clippingRectangle;
    };

    zxcv.SpriteNode.prototype.show        = zxcv.VisualNode.prototype.show;
    zxcv.SpriteNode.prototype.hide        = zxcv.VisualNode.prototype.hide;
    zxcv.SpriteNode.prototype.addChild    = zxcv.VisualNode.prototype.addChild;
    zxcv.SpriteNode.prototype.removeChild = zxcv.VisualNode.prototype.removeChild;
    zxcv.SpriteNode.prototype.draw = function (g) {
        if (this.transform && this.texture) {
            g.push(this.transform.matrix);
            g.draw(this.texture, 0, 0, this.originX, this.originY, this.clippingRectangle);
            g.pop();
        }

        zxcv.VisualNode.prototype.draw.call(this, g);
    }
}